package com.doumuxie.service.impl;

import com.doumuxie.dto.PermissionDto;
import com.doumuxie.dto.UserDto;
import com.doumuxie.mapper.PermissionMapper;
import com.doumuxie.mapper.UserMapper;
import com.doumuxie.utils.SysCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author doumuxie https://gitee.com/lyears/
 * @version 1.0
 * @date 2020/2/16 9:43
 * @description 自定义  Security 的 UserDetailService
 **/
@Service
public class SecurityUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    @SuppressWarnings("all")
    private UserMapper userMapper;

    @Autowired
    @SuppressWarnings("all")
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从内存查询数据
//        String gensalt = BCrypt.hashpw("123123",BCrypt.gensalt());
//        System.err.println(gensalt);
//        return User.withUsername("admin").password(gensalt).authorities("r1").build();

        // 从数据库查询数据
        UserDto userDto = new UserDto();
        // 用户名
        userDto.setUsername(username);
        // 未删除
        userDto.setDeleteState(SysCode.DELETE_STATE.NO);

        UserDto result = userMapper.selectByExample(userDto);
        if (result == null) {
            return null;
        }
        List<String> authList = new ArrayList<>();
        // 查询权限
        List<PermissionDto> permissions = permissionMapper.permissionList(result.getId());
        permissions.forEach(p -> authList.add(p.getCode()));
        return User.withUsername(result.getUsername()).password(result.getPassword()).authorities(authList.toArray(new String[0])).build();
    }
}
